<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="620px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="130px"
      class="demo-ruleForm"
    >
      <el-form-item label="服务商名称" prop="name">
        <el-input
          v-model.trim="formData.name"
          maxlength="30"
          placeholder="请输入姓名"
          :disabled="isView"
        />
      </el-form-item>
      <el-form-item label="代理商名称" prop="agentId">
        <el-select
          :model-value="formData.agentId"
          placeholder="请输入代理商名称搜索"
          :disabled="isView"
          clearable
          filterable
          remote
          :loading="agentLoading"
          :remote-method="searchAgent"
          @change="handleAgentIdChange"
          style="width: 100%"
        >
          <el-option
            v-for="agent in agentOptions"
            :key="agent.id"
            :label="`${agent.agentName} (${agent.mobile})`"
            :value="agent.id"
          />
        </el-select>

      </el-form-item>
      <el-form-item label="联系方式" prop="contactPhone">
        <el-input
          v-model.trim="formData.contactPhone"
          type="text"
          placeholder="请输入手机号码"
          :disabled="isView"
          @input="handleMobileInput"
        />
      </el-form-item>
      <el-form-item label="登录账号" prop="username">
        <el-input
          v-model.trim="formData.username"
          maxlength="30"
          placeholder="请输入登录代理商后台的账号"
          :disabled="isView"
        />
      </el-form-item>
      <el-form-item label="登录密码" prop="password" :required="!isEdit">
        <el-input
          v-model="formData.password"
          maxlength="30"
          :placeholder="isEdit ? '为空则不修改原密码' : '请输入密码'"
          :disabled="isView"
          type="password"
        />
      </el-form-item>
      <el-form-item label="到期时间" prop="expireTime">
        <el-date-picker
          v-model="formData.expireTime"
          type="date"
          placeholder="选择日期"
          value-format="YYYY/MM/DD"
          :disabled-date="disabledDate"
          :disabled="isView"
        />
      </el-form-item>

      <el-form-item label="账号是否启用" prop="status">
        <el-radio-group v-model="formData.status" :disabled="isView">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 服务商关联会员 请输入会员手机号码（如果是会员可自动关联，不是会员不允许关联）-->
      <el-form-item label="服务商关联会员" prop="bindMemberPhone">
        <el-input
          v-model.trim="formData.bindMemberPhone"
          :disabled="isEdit"
          placeholder="请输入会员手机号码"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">{{ isView ? '关闭' : '取消' }}</el-button>
        <el-button v-if="!isView" type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { getAgentUsersDetail, getAagentUsers } from '@/api/mall/agent/index'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { formateDateday } from '@/utils/formatTime'
import { createAgent, updateAgent } from '@/api/mall/agent/index'
// import { useUploadToWebDisk } from '@/views/ai/webdisk/upload'
import { getAreaTree } from '@/api/system/area/index'
import { useUpload } from '@/components/UploadFile/src/useUpload'
import ServiceApi from '@/api/application/service'
import { bind } from 'min-dash'
import { log } from 'console'
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  type: {
    type: String,
    default: 'add'
  },
  currentRow: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'success'])
const memberTotal = ref(0)
const dialogVisible = ref(props.modelValue)
const formRef = ref<FormInstance>()
const fileList = ref<{ name: string; url: string }[]>([])

// 使用上传组件的钩子
const { uploadUrl, httpRequest } = useUpload((percentage: number) => {
  // 这里可以处理上传进度
})

// 计算属性
const isView = computed(() => props.type === 'view')
const isEdit = computed(() => props.type === 'edit')
const dialogTitle = computed(() => {
  const titles = {
    add: '新增服务商',
    edit: '编辑服务商',
    view: '查看服务商'
  }
  return titles[props.type as keyof typeof titles]
})

// 表单数据
const formData = ref({
  name: '',
  contactPhone: '',
  username: '',
  password: '',
  expireTime: '',
  status: 1,
  bindMemberPhone: '',
  agentId: undefined,
  agentName: ''
})

const agentInfo = ref<any>(null)
const agentOptions = ref<any[]>([])
const agentLoading = ref(false)
const agentInfoLoading = ref(false)

// 搜索代理商
const searchAgent = async (query: string) => {
  if (!query) {
    agentOptions.value = []
    return
  }

  agentLoading.value = true
  try {
    const res = await getAagentUsers({
      agentName: query,
      pageNo: 1,
      pageSize: 20
    })
    agentOptions.value = res.list || []
  } catch (error) {
    console.error('搜索代理商失败:', error)
    ElMessage.error('搜索代理商失败')
    agentOptions.value = []
  } finally {
    agentLoading.value = false
  }
}

const handleAgentIdChange = async (val) => {
  // 更新formData.agentId的值
  formData.value.agentId = val || undefined
  agentInfo.value = null
  if (!val) return
  try {
    const res = await getAgentUsersDetail({ id: val })
    if (res.agentId) {
      agentInfo.value = res
    } else {
      agentInfo.value = null
      ElMessage.warning('未找到该代理商ID对应的信息')
    }
  } catch (error) {
    agentInfo.value = null
    ElMessage.error('查询代理商信息失败')
  }
}

// 表单验证规则
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入商名称', trigger: 'blur' }],
  agentName: [
    { required: false, message: '请输入代理商名称', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  username: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
  password: [
    {
      required: true,
      message: '请输入登录密码',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (props.type === 'add' && (!value || value.trim() === '')) {
          callback(new Error('请输入登录密码'))
        } else {
          callback()
        }
      }
    }
  ],
  expireTime: [{ required: true, message: '请选择到期时间', trigger: 'change' }],
  bindMemberPhone: [
    { required: true, message: '请输入会员手机号码', trigger: 'blur' },

    {
      validator: (rule, value, callback) => {
        const test = /^1[3-9]\d{9}$/
        if (!test.test(value)) {
          callback(new Error('请输入正确手机号'))
          return
        }
        console.log('value++++++', value)
        if (value && !memberTotal.value) {
          ServiceApi.getServiceMemberPage({ mobile: value, pageNo: 1, pageSize: 10 }).then(
            (res) => {
              console.log('获取会员关联结果:', res.total)
              memberTotal.value = res.total
              if (!res.total) {
                console.log('此手机号暂无会员关联')
                callback(new Error('此手机号暂无会员关联'))
              } else {
                callback()
              }
            }
          )
        } else {
          callback()
        }
        // callback()
      }
    }
  ]
})
// 禁用今天之前的日期
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 获取代理商详情
const getAgentInfo = async () => {
  // [{agentArea: "130203"
  // agentAreaName: "路北区"
  // fullName: "河北省唐山市路北区"
  // level:4}]
  try {
    const data = props.currentRow

    // 先清空代理商选项，防止显示数字
    agentOptions.value = []

    // 设置表单数据
    Object.assign(formData.value, {
      name: data.name,
      contactPhone: data.contactPhone || '',
      username: data.username || '',
      expireTime: formateDateday(data.expireTime || ''),
      bindMemberPhone: data.bindMemberPhone || '',
      status: data.enabled ? 1 : 0,
      agentId: data.agentId || undefined
    })

    // 如果有agentId，获取代理商信息用于显示
    if (data.agentId) {
      agentInfoLoading.value = true
      try {
        const agentDetail = await getAgentUsersDetail({ id: data.agentId })
        if (agentDetail && agentDetail.agentId) {
          // 设置agentOptions以便el-select正确显示
          agentOptions.value = [{
            id: agentDetail.agentId,
            agentName: agentDetail.agentName || agentDetail.name,
            mobile: agentDetail.mobile || agentDetail.contactPhone
          }]
        }
      } catch (error) {
        console.error('获取代理商详情失败:', error)
        ElMessage.warning('获取代理商详情失败')
      } finally {
        agentInfoLoading.value = false
      }
    }
  } catch (error) {
    console.error('获取代理商详情失败:', error)
    ElMessage.error('获取代理商详情失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  // 登录账号：用户账号由 数字组成
  if (formData.value.username) {
    const testUsername = /^[0-9]+$/.test(formData.value.username)
    if (!testUsername) {
      ElMessage.warning('登录账号只能由数字组成')
      return
    }
  }

  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      const sendData = {
        name: formData.value.name,
        contactPhone: formData.value.contactPhone,
        username: formData.value.username,
        password: formData.value.password,
        expireTime: new Date(formData.value.expireTime).getTime(),
        enabled: formData.value.status ? true : false,
        bindMemberPhone: formData.value.bindMemberPhone,
        agentId: formData.value.agentId
      }
      // return
      try {
        if (props.type === 'add') {
          await ServiceApi.createService(sendData)
          ElMessage.success('添加成功')
        } else if (props.type === 'edit') {
          // 如果是编辑状态且密码为空，则不发送密码字段
          if (!formData.value.password) {
            const { password, ...rest } = sendData
            await ServiceApi.updateService({ ...rest, id: props.currentRow.id })
          } else {
            await ServiceApi.updateService({ ...sendData, id: props.currentRow.id })
          }
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        emit('success')
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 关闭弹窗
const handleClose = () => {
  emit('update:modelValue', false)
  formRef.value?.resetFields()
  fileList.value = []
  // 重置表单数据
  Object.assign(formData.value, {
    name: '',
    contactPhone: '',
    username: '',
    password: '',
    expireTime: '',
    type: '',
    status: 1,
    bindMemberPhone: '',
    agentId: undefined
  })
  // 重置代理商相关状态
  agentOptions.value = []
  agentInfoLoading.value = false
}

// 监听弹窗显示状态
watch(
  () => props.modelValue,
  async (val) => {
    if (val && props.type !== 'add') {
      // 编辑模式下，先加载数据再显示弹窗
      await getAgentInfo()
      dialogVisible.value = true
    } else {
      // 新增或查看模式直接显示
      dialogVisible.value = val
    }
  }
)

watch(
  () => dialogVisible.value,
  (val) => {
    emit('update:modelValue', val)
  }
)

// 只允许输入数字的处理函数
const handleMobileInput = () => {
  formData.value.contactPhone = formData.value.contactPhone.replace(/[^\d]/g, '')
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.file-name-ellipsis {
  display: inline-block;
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}
</style>
